package org.ontobrowser.ontoextract;

import java.util.ArrayList;
import java.util.List;


import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class RDFDomUtil {

	public static final String RDFSCHEMA_NS = "http://www.w3.org/2000/01/rdf-schema#";
	public static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
	public static final String TYPE_CLASS = "Class";
	public static final String TYPE_PROPERTY = "Property";
	
	// class properties
	
	public static final String label ="label";
	public static final String isDefinedBy = "isDefinedBy";
	public static final String subClassOf = "subClassOf";
	public static final String comment = "comment";
	public static final String RDFS_DOMAIN = "domain";
	

	public static NodeList getClassElements(Element element) {
		return getClassElements(element, TYPE_CLASS, RDFSCHEMA_NS);
	}

	public static NodeList getClassElements(Element element, String localName,
			String ns) {
		NodeList nodeList = element.getElementsByTagNameNS(ns, localName);

		return nodeList;
	}

	public static List<Property> getElementProperies(String resource, Element element) {
		List<Property> properties = new ArrayList<Property>();
		
		NodeList nodeList = element.getElementsByTagNameNS(RDF_NS, TYPE_PROPERTY);
		
		for(int i=0; i<nodeList.getLength(); i++) {
	    	Element property = (Element) nodeList.item(i);
	    	String domain = getPropertyDomain(property);
	    	
	    	if(domain!= null && domain.equals(resource))
	    	{
	    		Property elementProperty = new Property(property);
	    		properties.add(elementProperty);
	    	}	    		
	    }
				
		return properties;
	}

	public static String getPropertyDomain(
			Element property) {
		Element domainNode = getChildNode(property, RDFSCHEMA_NS, RDFS_DOMAIN);
		if(domainNode != null) {
			return getElementAttributeValue(domainNode, RDF_NS, "resource");
		}
		
		return null;		
	}

	public static String getElementAttributeValue(Element classNode,
			String nameSpace, String attribute) {
		Attr attr = classNode.getAttributeNodeNS(nameSpace, attribute);
		if(attr == null) { // simple element
			Element simpleElement = RDFDomUtil.getChildNode(classNode, nameSpace, attribute);
			if(simpleElement != null)
				return simpleElement.getTextContent();			
		} else
			return attr.getNodeValue();
		
		return null;
	}

	public static Element getChildNode(Element propertyNode,
			String nameSpace, String localName) {
		NodeList nodelist = propertyNode.getElementsByTagNameNS(nameSpace, localName);		
		
		if(nodelist.getLength()>0)
			return (Element) nodelist.item(0);
		
		return null;
	}
}
